package com.tool.cn.use.search.map;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tool.cn.util.StringUtil;

/**
 * 
 * @author wangzonghui
 * @date 2022年4月24日 下午4:19:19 
 * @Description 精确查询map
 */
public class EqualMap{
	
	private final Logger log = LoggerFactory.getLogger(this.getClass());

	private Map<String,List<String>> dataMap=new Hashtable<>();
	
	private Map<String,String> recordMap=new Hashtable<>();
	
	public boolean add(String key, String data) {
		List<String> tmpList;
		try {
			if(dataMap.containsKey(key)) {
				tmpList=dataMap.get(key);
			}else {
				tmpList=new ArrayList<>();
			}

			if(!tmpList.contains(data)) {
				tmpList.add(data);
				dataMap.put(key, tmpList);
				
				//添加记录
				recordMap.put(data, key);
			}else {
				log.error("Key:{} Data {} Have Map",key,data);
			}
			
		} catch (Exception e) {
			log.error("Add Key {} Of Data:{} Error",key,data);
			return false;
		}
		return true;
	}

	/**
	 * 删除元素
	 * @param key 
	 * @param data value值
	 * @return
	 */
	public boolean remove(String key,String data) {
		List<String> tmpList;
		try {
			if(dataMap.containsKey(key)) {
				tmpList=dataMap.get(key);
				if(tmpList.removeIf( e -> e.equals(data))) {
					
					if(tmpList.size()>0) {
						dataMap.put(key, tmpList);
					}else {
						dataMap.remove(key);
					}
				}
				
				//删除记录
				recordMap.remove(data);
			}
		} catch (Exception e) {
			log.error("Remove Key {} Of Data:{} Error",key,data);
			return false;
		}
		return true;
	}
	
	/**
	 * 删除元素
	 * @param data value值
	 * @return
	 */
	public boolean remove(String data) {
		if(recordMap.containsKey(data)) {
			String value=recordMap.get(data);
			return remove(value, data);
		}
		return true;
	}

	/**
	 * 查询元素
	 * @param key 
	 * @return
	 */
	public List<String> search(String key) {
		if(dataMap.containsKey(key)) {
			return dataMap.get(key);
		}
		
		return new ArrayList<>();
	}
	
	@Override
	public String toString() {
		if(dataMap.size()>0) {
			return StringUtil.mapToString(dataMap);
		}
		return "";
	}

}
